<template>
  <div class="card content-box">
    <el-form ref="ruleFormRef" :model="ruleForm" :rules="rules" label-width="140px">
      <el-row :gutter="20">
        <el-col :span="24">
          <el-form-item :label="t('system.department.name')" prop="name">
            <el-input v-model="ruleForm.name" />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('system.department.parent_name')" prop="parent_id">
            <el-select-v2
              v-model="ruleForm.parent_id"
              filterable
              remote
              :remote-method="remoteMethod"
              clearable
              :options="options"
              :loading="loading"
            />
          </el-form-item>
        </el-col>
        <el-col :span="24">
          <el-form-item :label="t('common.status')" prop="status">
            <el-radio-group v-model="ruleForm.status">
              <el-radio :label="10" border>{{ $t("common.normal") }}</el-radio>
              <el-radio :label="20" border>{{ $t("common.disable") }}</el-radio>
            </el-radio-group>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row :gutter="20">
        <el-form-item>
          <el-button type="primary" @click="submitForm(ruleFormRef)">保存</el-button>
          <el-button @click="resetForm(ruleFormRef)">重置</el-button>
        </el-form-item>
      </el-row>
    </el-form>
  </div>
</template>

<script setup lang="ts" name="dynamicForm">
import { reactive, ref, onBeforeMount } from "vue";
import { useI18n } from "vue-i18n";
import { useRoute } from "vue-router";
import type { FormInstance, FormRules } from "element-plus";
import { ElMessage } from "element-plus";
import { departmentCreate, departmentModify, departmentDetail, departmentList } from "@/api/modules/system";
import { useTabsStore } from "@/stores/modules/tabs";
import { useKeepAliveStore } from "@/stores/modules/keepAlive";

const route = useRoute();
const { t } = useI18n();

const options = ref([
  {
    label: "顶级部门",
    value: 0
  }
]);
const loading = ref(false);
const ruleForm = reactive({
  id: 0,
  name: "",
  parent_id: 0,
  status: 10
});

let timeoutId = null;
const remoteMethod = (name?: string) => {
  if (timeoutId) {
    clearTimeout(timeoutId);
  }

  timeoutId = setTimeout(() => {
    departmentList({ name: name }).then(response => {
      options.value = [];
      if (!name) {
        options.value.push({
          label: "顶级部门",
          value: 0
        });
      }

      response.data.list.forEach(item => {
        options.value.push({
          label: item.name,
          value: item.id
        });
      });
    });
  }, 300);
};

const tabStore = useTabsStore();
const keepAliveStore = useKeepAliveStore();
const ruleFormRef = ref<FormInstance>();

const rules = reactive<FormRules>({
  name: [{ required: true, message: t("system.position.rule.name"), trigger: "blur" }],
  status: [{ required: true, message: t("common.rule.status"), trigger: "blur" }]
});

const submitForm = async (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  await formEl.validate(valid => {
    if (valid) {
      const action = ruleForm.id > 0 ? departmentModify : departmentCreate;
      action(ruleForm).then(response => {
        ElMessage.success(response.message);
        setTimeout(() => {
          if (route.meta.isAffix) return;
          tabStore.removeTabs(route.fullPath);
          keepAliveStore.removeKeepAliveName(route.name as string);
        }, 200);
      });
    } else {
      ElMessage.error("请根据提示输入信息！");
    }
  });
};

const resetForm = (formEl: FormInstance | undefined) => {
  if (!formEl) return;
  formEl.resetFields();
};

const getDetail = (id?: Number) => {
  if (id > 0) {
    departmentDetail({ id }).then(response => {
      ruleForm.id = response.data.id;
      ruleForm.name = response.data.name;
      ruleForm.parent_id = response.data.parent_id;
      ruleForm.status = response.data.status;
    });
  }
};

onBeforeMount(() => {
  getDetail(route.params.id);
  remoteMethod();
});
</script>

<style scoped lang="scss">
@import "./edit.scss";
</style>
